import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:hippo_app/models/data_list_container.dart';
import 'package:hippo_app/values/app_value.dart';
import 'package:hippo_app/values/style_value.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';

import '../../utils/common_util.dart';
import '../empty/empty.dart';

class DataListContainer extends StatefulWidget {
  Function(BuildContext context, dynamic item) listBodyBuilder;
  Function(DataListContainerQueryParam param) getData;

  bool usePagination;

  DataListContainer({
    super.key,
    required this.listBodyBuilder,
    required this.getData,
    this.usePagination = true,
  });

  @override
  DataListContainerState createState() => DataListContainerState();
}

class DataListContainerState extends State<DataListContainer> {
  bool isLastPage = false;
  List<dynamic> dataList = [];
  int currentPage = 1;

  @override
  void initState() {
    super.initState();
    getData();
  }

  @override
  void dispose() {
    super.dispose();
  }

  getData() async {
    DataListContainerQueryParam param = DataListContainerQueryParam();

    if (widget.usePagination) {
      param.pageSize = AppValue.pageSize;
      param.currentPage = currentPage;
    }

    var res = await widget.getData(param);

    if (null != res.data && res.data["isSuccess"]) {
      if (null != res.data["data"] && res.data["data"].length > 0) {
        dataList.addAll(res.data["data"]);
        isLastPage = widget.usePagination ? false : true;
      } else {
        isLastPage = true;
      }
      setState(() {});
    } else {
      SmartDialog.showToast(res.data["msg"]);
    }
  }

  Future<void> refresh() async {
    CommonUtil.textInputHide();
    CommonUtil.debounce(() async {
      if (widget.usePagination) {
        currentPage = 1;
      }

      isLastPage = false;
      dataList = [];
      await getData();
    }, null)();
  }

  Widget buildList() {
    return Padding(
      padding: const EdgeInsets.all(10.0),
      child: Column(
        children:
            dataList
                .map(
                  (item) =>
                      Container(child: widget.listBodyBuilder(context, item)),
                )
                .toList(),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return dataList.isNotEmpty
        ? buildList()
        : Padding(
          padding: const EdgeInsets.only(top: 15.0),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Empty(),
              InkWell(
                onTap: refresh,
                child: Text(
                  AppLocalizations.of(context)!.retryBtnLabel,
                  style: StyleValue.dataListContainerReloadTxtStyle,
                ),
              ),
            ],
          ),
        );
  }
}
